############################################################ ########### #
#
# Project: Stability and change in the opinion-policy relationship
# 
# This script cleans and merges CCES data with minimum wage prefs 
# 
# 2022.09.30. 
############################################################ ########### #


library(rio)
library(tidyverse)

# create a lookup table for inputstate
# CCES 2019 has nice labels

# raw19 <- import("A-original-data/CCES19.RData") 
# 
# state_lookup <- tibble(
#         inputstate = attributes(raw19$inputstate)$labels,
#         state = attributes(attributes(raw19$inputstate)$labels)$names
# )
# 
# saveRDS(state_lookup, file = "B-analysis-data/cces_statelookup.rds")

# load raw CCES datasets
raw16 <- import("A-original-data/CCES16.RData")
raw18 <- import("A-original-data/CCES18.RData") 
raw20 <- import("A-original-data/CCES20.csv")

state_lookup <- readRDS("B-analysis-data/cces_statelookup.rds")


# clean 2016  data
cc16 <- raw16 %>% 
        # limit to state, minimum wage pref and survey weights
        transmute(state = as.character(inputstate), 
                  minwage = ifelse(CC16_351K == "For", 1, 0),
                  commonweight_vv)  

# repeat for 2018
cc18 <- raw18 %>% 
        transmute(inputstate, 
                  minwage = ifelse(CC18_414A == 1, 1, 0),
                  commonweight) %>% 
        # add proper state names
        left_join(state_lookup) 

# repeat for 2020
cc20 <- raw20 %>% 
        transmute(inputstate, 
                  minwage = ifelse(CC20_350b == 1, 1, 0),
                  commonweight) %>% 
        left_join(state_lookup)

# calculate weighted averages for minimum wage pref in each state for each year.
mw_16 <- cc16 %>% 
        group_by(state) %>% 
        summarise(minwage = weighted.mean(minwage, commonweight_vv, na.rm = T),
                  year = 2016) 

mw_18 <- cc18 %>% 
        group_by(state) %>% 
        summarise(minwage = weighted.mean(minwage, commonweight, na.rm = T), 
                  year = 2019 )

mw_20 <- cc20 %>% 
        group_by(state) %>% 
        summarise(minwage = weighted.mean(minwage, commonweight, na.rm = T),
                  year = 2021)

# combine into single df. 
mw <- bind_rows(mw_16, mw_18, mw_20)
write.csv(mw, file = "B-analysis-data/cces_estimates.csv")